//
//  OosServiceDao.m
//  Oos4ios
//
//  Created by Pablo Gonzalez on 3/17/11.
//  Copyright 2011 11870.com. All rights reserved.
//

#import <oos4ios/DAOs/OosServiceDao.h>
#import "../../Atom/Services/OosAtomService.h"
#import "../../Atom/Queries/OosServiceQuery.h"
#import "../../Atom/Queries/OosSearchQuery.h"
#import "../../Atom/Feeds/OosServiceFeed.h"
#import "../../Atom/Entries/OosServiceEntry.h"
#import "../../Parsers/OosServiceFeedParser.h"
#import "../../Parsers/OosServiceEntryParser.h"
#import "OosDao+Internal.h"

@implementation OosServiceDao

@synthesize serviceSlug = mServiceSlug;
@synthesize userSlug = mUserSlug;

+ (OosServiceDao *) dao
{
	return [[OosServiceDao new] autorelease];
}

+ (OosServiceDao *) daoFromUser:(OosUser *)user
{
	return [[[OosServiceDao alloc] initFromUser: user] autorelease];
}

+ (OosServiceDao *) daoFromUserSlug:(NSString *)userSlug
{
	return [[[OosServiceDao alloc] initFromUserSlug: userSlug] autorelease];
}

- (OosServiceDao *) initFromUser:(OosUser *)user
{
	self = [self initFromUserSlug:[user slug]];
	if (self) {
		self->mUser = [user retain];
	}
	return self;
}

- (OosServiceDao *) initFromUserSlug:(NSString *)userSlug
{
	self = [self init];
	if (self) {
		self->mUserSlug = [userSlug retain];
	}
	return self;
}

- (OosQuery *) query
{
	OosQuery *query = nil;
    if (self.serviceSlug) {
        if (self.userSlug) {
            query = [OosServiceQuery queryWithUserSlug:self.userSlug 
                                       withServiceSlug:self.serviceSlug];
        } else {
            query = [OosServiceQuery queryWithServiceSlug: self.serviceSlug];
        }
    } else {
        if (self.userSlug) {
            query = [OosServiceQuery queryWithUserSlug:self.userSlug];
        } else {
            query = [OosSearchQuery query];
        }
    }
	[query packStore: self.options];
	return query;
}

- (OosDaoTicket *)create: (OosObject *)object 
            withCallback: (id<IOosDaoCreateCallback>)callback
{
    if ([object isKindOfClass:[OosService class]]) {
        self.options.reviewOptions.service = (OosService *) object;
    } else if([object isKindOfClass:[OosReview class]]) {
        self.options.reviewOptions.review = (OosReview *) object;
    } else {
        return [super create:object withCallback:callback];
    }
    return [super create:nil withCallback:callback];
}

- (void)initAtomService:(OosAtomService *)atomService
{
    atomService.feedClass = [OosServiceFeed class];
    atomService.entryClass = [OosServiceEntry class];
}

- (id<IOosEntryParser>) entryParser
{
    return [OosServiceEntryParser instance];
    return nil;
}

- (id <IOosFeedParser>) feedParser
{
    BOOL user = self.userSlug != nil;
    BOOL service = self.serviceSlug != nil;
    if ((user ^ service) || !(user && service)) {
        return [OosServiceFeedParser instance];
    }
	return nil;
}

- (void)dealloc
{
    self.userSlug = nil;
    self.serviceSlug = nil;
    [mUser release];
    [super dealloc];
}

@end
